package xin.fallen.serviceimpl;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import xin.fallen.service.PicManagerSer;
import xin.fallen.util.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Author: Fallen
 * Date: 2017/3/9
 * Time: 14:52
 * Usage:
 */
@Service
public class PicManagerSerSerImpl implements PicManagerSer {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    public String download(String mediaId, String code) {
        if (mediaId == null) {
            return null;
        }
        byte[] b = PicDownloader.download(TokenCourier.getAccessToken(), mediaId);
        File root = new File(ConfigReader.getValue(IniUtil.getValue(code, "pic_dir")));
        File dir = new File(root + File.separator + FileManagerSerImpl.sdf.format(new Date()));
        if (!dir.isDirectory()) {
            dir.mkdir();
        }
        String fileName = UUID.randomUUID().toString() + ".JPG";
        File pic = new File(dir + File.separator + fileName);
        try {
            FileUtils.writeByteArrayToFile(pic, b);
        } catch (IOException e) {
            log.error("图片存储异常，原因是：{}", e.getMessage());
            return null;
        }
        String replacement = ConfigReader.getValue(IniUtil.getValue(code, "pic_prenew"));
        String beRplacement = ConfigReader.getValue(IniUtil.getValue(code, "pic_preold"));
        return pic.getAbsolutePath().replace(beRplacement, replacement).replace("\\", "/");
    }
}